﻿using Furion;
using Furion.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Project1.Core;
using System;
using System.IO;

namespace Project1.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddJwt<JwtHandler>();
            // 允许跨域
            services.AddCorsAccessor();
            // 远程请求
            services.AddRemoteRequest();
            // 任务调度
            services.AddSchedule(options =>
            {
                options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
            });
            services.AddControllers()
                    .AddInjectWithUnifyResult();

            // 日志记录
            if (App.GetConfig<bool>("Logging:File:Enabled")) // 日志写入文件
            {
                Array.ForEach(new[] { LogLevel.Information, LogLevel.Warning, LogLevel.Error }, logLevel =>
                {
                    services.AddFileLogging(options =>
                    {
                        options.FileNameRule = fileName => string.Format(fileName, DateTime.Now, logLevel.ToString()); // 每天创建一个文件
                        options.WriteFilter = logMsg => logMsg.LogLevel == logLevel; // 日志级别
                        options.HandleWriteError = (writeError) => // 写入失败时启用备用文件
                        {
                            writeError.UseRollbackFileName(Path.GetFileNameWithoutExtension(writeError.CurrentFileName) + "-oops" + Path.GetExtension(writeError.CurrentFileName));
                        };
                    });
                });
            }
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}